package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.model.Message;
import com.conversationboard.model.NoSuchThreadException;
import com.conversationboard.model.Thread;
import com.conversationboard.model.User;

@WebServlet(name = "AdminEditMessageControllerServlet", urlPatterns = "/Admin/AdminEditMessageControllerServlet")
public class AdminEditMessageControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -2401252824850235961L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		/*
		 * Pick up the board, thread and message IDs from the HTTP GET
		 * parameters, get the message and forward to the edit message JSP
		 */

		String boardId = (String) request.getParameter("boardid");
		int boardIdNumber = Integer.parseInt(boardId);

		String threadId = (String) request.getParameter("threadid");
		int threadIdNumber = Integer.parseInt(threadId);

		String messageId = (String) request.getParameter("messageid");
		int messageIdNumber = Integer.parseInt(messageId);

		String userId = request.getUserPrincipal().getName();

		try {

			User user = User.get(userId);

			// if (user.isBoardAdmin(boardIdNumber)) {
			// Removed 18-Feb. Can't trust board admins to have access to HTML.

			if (user.isSiteAdmin()) {

				Thread thread = Thread.get(boardIdNumber, threadIdNumber);
				Message message = thread.getMessage(messageIdNumber);

				request.setAttribute("message", message);

				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/Admin/editmessage.jsp");
				dispatcher.forward(request, response);
				return;

			} else {

				request.setAttribute("message", "You are not authorised to perform this operation.");

				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/Admin/editmessage.jsp");
				dispatcher.forward(request, response);
				return;
			}

		} catch (NoSuchThreadException e) {
			throw new ServletException(e);
		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
